<?php
declare (strict_types = 1);

namespace app\command;

use app\model\Profitlog;
use app\model\User;
use app\model\UserMoneyLog;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class HandleProfit extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('handle-income')
            ->setDescription('处理用户收益');
    }

    protected function execute(Input $input, Output $output)
    {
        Db::startTrans();
        try {
            $users = User::where("freeze_money", ">", 0)->lock(true)->select();
            foreach($users as $user) {

                $freezeMoney = $user->freeze_money;
                $user->balance = bcadd($user->balance, $freezeMoney, 2);
                $user->freeze_money = 0;
                $user->save();

                if($freezeMoney > 0) {
                    UserMoneyLog::create([
                        'user_id' => $user->id,
                        'type' => 1,
                        'cate_id' => 4,
                        'amount' => $freezeMoney,
                        'remark' => "冻结资金转入 +" . $freezeMoney
                    ]);

                    UserMoneyLog::create([
                        'user_id' => $user->id,
                        'type' => 2,
                        'cate_id' => 5,
                        'amount' => $freezeMoney,
                        'remark' => "冻结资金转出 -" . $freezeMoney
                    ]);
                }

                Profitlog::where("uid", $user->id)->where("status", 0)->update(['status'=>1]);

                $output->writeln('处理用户：'.$user->username."的冻结金额完成");
            }

          
            Db::commit();
            
        } catch (\Throwable $th) {
            Db::rollback();
        }

        // 指令输出
        $output->writeln('处理完成');
    }
}
